Uec3.initialOperationWin = Ext.extend(Ext.UecWindow, {
	wMaskCol:new Ext.util.MixedCollection(false),
	constructor:function(config){
		this.buttonAjax=Uec3.App.Uec3Ajax;
		this.initialItem_grid=this.getInitialItemGrid.createDelegate(this)();
		this.itemWindow=this.getItemWindow();
		this.getInitialContainer();
		config=Ext.apply(config||{},{items:[this.editForm,this.initialItem_grid,this.readOnlyForm]});
		Uec3.initialOperationWin.superclass.constructor.call(this,config);
		this.params=config.params||{};
	},
    getInitialItemGrid:function(){
    	this.resultTpl = new Ext.XTemplate(
	      '<tpl for="."><div class="x-combo-list-item">',
	          '{code} {sourceName} {tempName}',             
	      '</div></tpl>'
	    );
    	this.initialItem_record = Ext.data.Record.create( [ {name : 'id'}, {name : 'initialId'}, {name : 'partId'}, {name : 'code'}, {name : 'source'}, {name : 'name'}, {name : 'measurementUnit'}, {name : 'partCategoryId'},
		{name : 'level1Name'}, {name : 'level2Name'}, {name : 'level1Id'}, {name : 'level1Id'}, {name : 'brand'}, {name : 'origin'}, {name : 'cost'}, {name : 'retailPrice'}, {name : 'insurancePrice'}, {name : 'minPrice'}, 
		{name : 'costAmout'}, {name : 'quantity'}, {name : 'costAmount'}, {name : 'shelf'}, {name : 'maxOnHand'}, {name : 'minOnHand'}, {name : 'swapCode'}, {name : 'storeId'}, {name : 'storeName'}, {name : 'checkResult'}, 
		{name : 'tempName'}, {name : 'storePyCode'}, {name : 'carModel'},{name : 'errorType'}]);
		
		this.ds_initialItem = new Ext.data.Store({
			proxy : new Ext.data.HttpProxy({url : Uec3.App.Constants.homeUrl+'/initialItem/extList.do'}),
			sortInfo:{field: "id", direction: "DESC"},
			pruneModifiedRecords : true,
			remoteSort:true,
			baseParams : {initialId:0},
			reader : new Ext.data.JsonReader( {totalProperty : 'totalProperty',root : 'root'}, 
			this.initialItem_record)
		});
		this.ds_postPartName_select= new Ext.data.JsonStore({
			url : Uec3.App.Constants.homeUrl+ '/initialItem/base!query.do',
			baseParams:{initialId:0},root:'root',totalProperty: "totalProperty",
			fields:[{name : 'id',type:'int'},{name : 'code',type:'string'},{name : 'tempName',type:'string'},{name : 'sourceName',type:'string'}]});
		this.ds_initialItem_other = new Ext.data.Store( {
			proxy : new Ext.data.HttpProxy({url : Uec3.App.Constants.homeUrl+'/initialItem/extList.do'}),
			sortInfo:{field: "id", direction: "DESC"},pruneModifiedRecords : true,remoteSort:true,
			baseParams : {initialId:0},
			reader : new Ext.data.JsonReader({totalProperty : 'totalProperty',root : 'root'}, this.initialItem_record)
		});
		
		var partPropertyComboBox=getPartpropertyLookUp(Uec3.App.Constants.homeUrl+'/part/queryPart!queryCombox.do');
		this.source_comboBox = Uec3.App.dictionary.getCombo("part_source",{hiddenName:'source',fieldLabel:"来源"});
		
		/* 文件导入 */
		var initialItem_form_file_buttons=[
			{text : '保存',iconCls:'icon-save',scope:this,handler : this.fileSave},
			{text : '重置',handler : function() {this.initialItem_form_file.getForm().reset();}}];
		this.fileuploadfield=new Ext.form.FileUploadField(
			{emptyText : '请选择Excel文件',fieldLabel : '上传文件:',name : 'excel',buttonText : '浏览...',
			listeners : {
				'fileselected' : function(fb, v) {
					if (Ext.util.Format.lowercase(v).lastIndexOf(".xls") != -1) {
						/* var fso = new ActiveXObject('Scripting.FileSystemObject');    
						 var file = fso.GetFile(fileName);  
						 alert(file.size);*/
					} else {
						Ext.Msg.alert("错误", "请选择正确的Excel文件");
						this.initialItem_form_file.getForm().reset();
					}
				}
			}
		});
		this.initialItem_form_file = new Ext.FormPanel({
			fileUpload : true,width : 300,frame : true,title : '文件上传(最大上传2000条)',
			bodyStyle : 'padding: 10px 10px 0 0px;',labelWidth : 60,
			defaults : {anchor : '98%',allowBlank : false},
			items : [this.fileuploadfield],
			buttons : initialItem_form_file_buttons
		});
		this.initialItem_win_file = Uec3.App.getDesktop().createWindowNoTaskMaxZIndex({
			layout : 'fit',width : 400,height : 150,closeAction : 'hide',plain : true,modal : true,
			items : [ this.initialItem_form_file ]
		});
		var cm_initialItem = new Ext.grid.ColumnModel([ new Ext.grid.RowNumberer(), 
			{header : '零件编码',width : 120,align:"right",dataIndex : 'code'}, 
			{header : '零件上传名称',width : 120,align:"left",dataIndex : 'tempName'}, 
			{header : '零件标准名称',width : 120,align:"left",dataIndex : 'name'}, 
			{header : '来源',width : 80,align:"left",dataIndex : 'source',renderer : Ext.util.Format.comboRenderer(this.source_comboBox)}, 
			{header : '车型',width : 100,align:"left",dataIndex : 'carModel'}, 
			{header : '单位',width : 55,align:"left",dataIndex : 'measurementUnit'}, 
			{header : '品牌',width : 75,align:"left",dataIndex : 'brand'}, 
			{header : '产地',width : 75,align:"left",dataIndex : 'origin'}, 
			{header : '数量',width : 50,align:"right",dataIndex : 'quantity'}, 
			{header : '仓库',width : 75,align:"left",dataIndex : 'storeName'}, 
			{header : '仓位',width : 75,align:"left",dataIndex : 'shelf'}, 
			{header : '进价',width : 75,align:"right",dataIndex : 'cost'}, 
			{header : '售价',width : 75,align:"right",dataIndex : 'retailPrice'}, 
			{header : '最低售价',width : 75,align:"right",dataIndex : 'minPrice'}, 
			{header : '上限库存',width : 80,align:"right",dataIndex : 'minOnHand'}, 
			{header : '下限库存',width : 80,align:"right",dataIndex : 'maxOnHand'}, 
			{header : '互换码',width : 75,align:"left",dataIndex : 'swapCode'}, 
			{header : '错误信息',width : 180,align:"left",dataIndex : 'checkResult'}]);
		
		var add={text : '新增',iconCls : 'icon-add',itemId:'add',handler : this.gridAdd.createDelegate(this)};
		var edit={text : '修改',itemId:'edit',iconCls : 'icon-edit',handler : this.gridEdit.createDelegate(this)};
		var del={text : '删除',itemId:'delete',iconCls : 'icon-del',scope:this,handler :this.gridDelete};
		var upload={text : 'Excel上传',itemId:'upload',iconCls : 'icon-file_upload',handler : this.fileUpload.createDelegate(this)};
		var excelDown={text : 'Excel模板下载',iconCls : 'icon-file_down',handler : this.fileDownload.createDelegate(this)};
		var dataDown={text : '数据导入工具下载',iconCls : 'icon-file_down',handler : this.toolsDownload.createDelegate(this)};
		var partPost={iconCls:'icon-search',text:'零件定位:'};
		this.postPartNameCombo=new Ext.form.ComboBox({
			xtype:'combo',name:"postPartName",width:250,fieldLabel:'零件编码',valueField:'code',name:'cccc',
			displayField : 'code',mode : 'remote',queryParam :'searchConditions',queryDelay:500,minChars :2,
			tpl: this.resultTpl,itemSelector: 'div.x-combo-list-item',pageSize:10,store : this.ds_postPartName_select,
			triggerAction : 'all',loadingText : '加载中...',emptyText : '至少输入两位零件编码'});
		var initialItem_grid=new Ext.grid.GridPanel({
			cm : cm_initialItem,store : this.ds_initialItem,columnLines :true,
			viewConfig : {
				getRowClass : function(record,rowIndex,rowParams,store){
					//禁用数据显示红色
					if(record.data.errorType==1){
						return 'x-grid-record-red';
					}else if(record.data.errorType==2){
						return 'x-grid-record-blue';
					}else {
						return '';
					}
					
				}
			},
			selModel : new Ext.grid.RowSelectionModel( {moveEditorOnEnter : true}),
			iconCls : 'icon-grid',loadMask : {msg : '数据加载中...'},stripeRows : true,
			autoScroll : true,flex:1,clicksToEdit : 1,
			tbar : new Ext.app.ModuleToolbar(
				['-',add,'-',edit,'-',del,'-',upload,'-',excelDown,'-',dataDown,'-',partPost,this.postPartNameCombo,'-'],
				{permission:31}),
			bbar : new Ext.PagingToolbar({
				pageSize : 10,store : this.ds_initialItem,displayInfo : true,displayMsg : '第 {0} - {1} 条  共 {2} 条',
				items:[
				"-",
				{xtype:"label",html:"<span style='color:red'>红色为错误记录</span>,<span style='color:blue'>蓝色为警告记录</span>,黑色为正常记录"}
				]}
				)
		});
		return initialItem_grid;
    },
    getItemWindow:function(){
    	this.itemFormCodeCombo=Uec3.App.fieldFactory.getCodeCombo();
		this.itemFormSourceCombo=Uec3.App.dictionary.getCombo("part_source",{name : 'source',hiddenName : 'source'});
		var nameField=new Ext.form.TextField({disabled:true,name:'name'});
		var measurementUnitField=new Ext.form.TextField({disabled:true,name:'measurementUnit'});
		var carModelField=new Ext.form.TextField({name:'carModel'});
		var brandField=new Ext.form.TextField({name:'brand'});
		var quantityField=new Ext.form.NumberField({name : 'quantity',allowNegative : false,allowBlank : false});
		this.itemFormCostField=new Ext.form.NumberField({name : 'cost',allowBlank : false,decimalPrecision:2,allowNegative : false});
		var retailPriceField=new Ext.form.NumberField({name : 'retailPrice',allowBlank : false,decimalPrecision:2,allowNegative : false});
		var insurancePriceField=new Ext.form.NumberField({name : 'insurancePrice',allowBlank : false,decimalPrecision:2,allowNegative : false});
		var minPriceField=new Ext.form.NumberField({name : 'minPrice',allowBlank : false,decimalPrecision:2,allowNegative : false});
		var originField=new Ext.form.TextField({name : 'origin'});
		var minOnHandField=new Ext.form.NumberField({name : 'minOnHand',allowNegative : false});
		this.itemFormMaxOnHandField=new Ext.form.NumberField({name : 'maxOnHand',allowNegative : false});
		this.itemFormStoreField=Uec3.App.fieldFactory.getStoreCombo();
		var shelfField=new Ext.form.TextField({name : 'shelf',allowBlank : true});
		var tempNameField=new Ext.form.TextField({name : 'tempName'});
		var swapCodeField=new Ext.form.TextField({name : 'swapCode'});
    	this.itemForm = new Ext.FormPanel({
			labelAlign : 'right',labelWidth : 80,bodyStyle : 'padding:5px',
			frame:true,border:false,defaultType : 'textfield',
			items:[{
			xtype:'fieldset',
			title:'零件信息',
			height:120,
			layout:'uec3grid',
		  	layoutConfig:{
			    hGrid:[15,34,15,34],
			    vGrid:[33,33,33],
			    usedGrid:[]
		    },
		    defaults:{enableKeyEvents : true},
			items:[
			{xtype:'label',text:'零件编码(*):'},this.itemFormCodeCombo,
			{xtype:'label',text:'来源(*):'},this.itemFormSourceCombo,
			{xtype:'label',text:'零件标准名称:'},nameField,
			{xtype:'label',text:'单位:'},measurementUnitField,
			{xtype:'label',text:'车型:'},carModelField,
			{xtype:'label',text:'品牌:'},brandField
			]},
			{
			xtype:'fieldset',
			title:'期初信息',
			height:200,
			layout:'uec3grid',
		  	layoutConfig:{
			    hGrid:[15,34,15,34],
			    vGrid:[16,16,16,16,16,16],
			    usedGrid:[]
		    },
		    defaults:{enableKeyEvents : true},
			items:[
			{xtype:'label',text:'数量(*):'},quantityField,
			{xtype:'label',text:'进价(*):'},this.itemFormCostField,
			{xtype:'label',text:'售价(*):'},retailPriceField,
			{xtype:'label',text:'保险价:'},insurancePriceField,
			{xtype:'label',text:'最低售价(*):'},minPriceField,
			{xtype:'label',text:'产地:'},originField,
			{xtype:'label',text:'下限库存:'},minOnHandField,
			{xtype:'label',text:'上限库存:'},this.itemFormMaxOnHandField,
			{xtype:'label',text:'仓库(*):'},this.itemFormStoreField,
			{xtype:'label',text:'仓位:'},shelfField,
			{xtype:'label',text:'零件上传名称'},tempNameField,
			{xtype:'label',text:'互换码:'},swapCodeField
			]
			},{xtype:'hidden',name:'id'}
			,{xtype:'hidden',name:'initialId'}
			]
    	});
    	var desktop = Uec3.App.getDesktop();
		var itemWindow = desktop.createWindowNoTask(
			{layout:'fit',width:620, closeAction:'hide',height:410,iconCls : 'acc-icon',maximizable : true,
			resizable:false,maximized:false,title:"期初明细-ESC关闭,ENTER向下选及保存",resizable :true,
			modal :true,closable:true,bodyStyle:'padding:5 5 5 5',animCollapse:true,
			items:[this.itemForm],
			buttons : [{text : '保存',iconCls:'icon-save',handler : this.itemSave.createDelegate(this)}, 
			{text : '关闭',iconCls:'icon-close',handler : this.itemClose.createDelegate(this)}],
			buttonAlign:'center'
		});
    	return itemWindow;
    },
    getInitialContainer:function(){
    	this.titleContainer=new Ext.Container({
    		layout:"uec3grid",
    		height:55,
    		layoutConfig:{
			    hGrid:[23,54,6,17],
			    vGrid:[75,25]
		    },
	    	items:[
	    		
	    		
	    	]
    	});
    	this.editForm=new Ext.FormPanel({
    		frame:true,
    		layout:"uec3grid",
    		height:100,
    		layoutConfig:{
			    hGrid:[6,17,54,6,17],
			    vGrid:[30,10,30,30]
		    },
    		items:[
    			{xtype:'label',
    			 html:'期&nbsp;&nbsp;&nbsp;&nbsp;初&nbsp;&nbsp;&nbsp;&nbsp;单',
	             style:'text-align:center; font-weight:bold;font-size:24px;font-family:FangSong_GB2312',
	             grid:[3,1,3,1]
    			},
	    		{xtype:'label',text : '单据号:',style:{fontSize:'14px'},grid:[4,1,4,1]},
	    		{xtype : 'textfield',name : 'code',readOnly :true,style:{background:'#dddddd'},grid:[5,1,5,1]},
	    		{xtype:"label",html:'<hr color="#34A4E0" />',grid:[1,2,5,2]},
    			{xtype:'label',text:'入库时间:',grid:[1,3,1,3]},
    			{xtype : 'datefield',allowBlank : false,name : 'gmtAccept',format : 'Y-m-d H:i:s',grid:[2,3,2,3]},
    			{xtype:'label',text:'备注:',grid:[1,4,1,4]},
    			{xtype : 'textfield',name : 'memo',grid:[2,4,5,4]},
    			{xtype:"hidden",name:"id"}
    			
    		]
    	});
    	this.readOnlyForm=new Ext.FormPanel({
    		frame:true,
    		layout:'uec3grid',
    		height:35,
    		layoutConfig:{
    			hGrid:[7,10,6,10,6,10,6,10,6,10,6,10],
				vGrid:[100]
		    },
		    defaults:{
		    	//style:{background:'#dddddd'},
		    	readOnly : true
		    },
    		items:[
    			{xtype:'label',text:"单据状态:"},{xtype : 'textfield',name : 'varName',style:{background:'#dddddd'}},
    			{xtype : 'label',text : '创建人:'},{xtype : 'textfield',name : 'creatorName',style:{background:'#dddddd'}},
    			{xtype : 'label',text : '创建时间:'},{xtype : 'textfield',name : 'gmtCreate',format : 'Y-m-d',style:{background:'#dddddd'}},
    			{xtype : 'label',text : '提交人:'},{xtype : 'textfield',name : 'submitterName',style:{background:'#dddddd'}},
    			{xtype : 'label',text : '提交时间:'},{xtype : 'textfield',name : 'gmtSubmit',format : 'Y-m-d',style:{background:'#dddddd'}},
    			{xtype : 'label',text : '总金额:'},{xtype : 'textfield',name : 'amount',style:{background:'#dddddd'}}
    		]
    	});
    },
    initEvents:function(){
    	Uec3.initialOperationWin.superclass.initEvents.call(this);
    	var _this=this;
    	this.source_comboBox.getStore().load();
    	this.itemFormSourceCombo.on('select',_this.autoFillDetailForm,_this);
    	this.itemFormCodeCombo.on('select',function(){this.itemForm.getForm().findField("source").clearValue();},_this);
    	this.itemFormCostField.on("blur",function(field){Uec3.App.companyConfig.setValuesToForm(_this.itemForm.getForm());});
    	this.itemFormMaxOnHandField.on("change",this.fEMaxOnHandField,_this);
    	this.postPartNameCombo.on("select",this.fEPostPartNameCombo,_this);
    	this.ds_initialItem_other.on("beforeload",this.fEItemOtherBeforeLoad,_this);
    	this.ds_initialItem_other.on("load",this.fEItemOtherLoa,_this);
    	formBingingKeys(this.itemForm,this.itemWindow);
    	this.on("show",this.fEAfterShow,this,{single:true});
    	//this.itemWindow.on("show",function(){this.itemForm.form.findField("code").focus(true,300);},this);
    },
    gridAdd:function() {
		if(this.itemForm.form.getEl()){
			this.itemForm.form.reset();
			this.itemForm.form.el.dom.reset();
		}else{
			this.itemForm.form.reset();
		}
		//setEnableField();
		this.itemForm.isAdd=true;
		this.itemWindow.show();
	},
	gridEdit:function() {
		var record = this.initialItem_grid.getSelectionModel().getSelected();
		if (record) {
			this.itemForm.isAdd=false;
			this.itemForm.getForm().loadRecord(record);
			this.itemWindow.show();
			var lookupbox=this.itemForm.getForm().findField("storeId");
			lookupbox.initializeValue({id:record.get("storeId"),name:record.get("storeName"),pyCode:record.get("storePyCode")});
		} else {
			Ext.MessageBox.alert("信息","请选择一行");
		}
	},
	gridDelete:function() {
		var record = this.initialItem_grid.getSelectionModel().getSelected();
		if (record) {
		} else {
			Ext.Msg.alert('信息',"请选择一行");
			return;
		}
		Ext.Msg.confirm('信息','确定要删除',function(btn) {
			if (btn == 'yes') {
				this.initialItem_grid.loadMask.show();
				Ext.Ajax.request( {
					params : {id : record.data.id,initialId:this.editForm.form.findField("id").getValue()},
					url : Uec3.App.Constants.homeUrl+'/initialItem/delete.do',
					scope:this,
					success : function(response) {
						var result = Ext.decode(response.responseText);
						if(result.success="OK"){
							this.ds_initialItem.remove(record);
							if(result.amount){
								this.readOnlyForm.form.findField("amount").setValue(result.amount);
							}
						}else{
							Ext.Msg.alert('信息',result.success);
						}
						this.initialItem_grid.loadMask.hide();
					},
					failure : function() {
						Ext.Msg.alert('网络问题!');
						this.initialItem_grid.loadMask.hide();
					}
				});
			}
		},this);
	},
	fileUpload:function() {
		this.initialItem_win_file.show();
		this.initialItem_form_file.getForm().reset();
	},
	fileDownload:function() {
		if (!Ext.fly('test')){ 
			var frm = document.createElement('form'); 
			frm.id = 'test'; 
			frm.style.display = 'none'; 
			document.body.appendChild(frm); 
		} 
		Ext.Ajax.request({ 
			url:Uec3.App.Constants.homeUrl+"/initial/download.do",
			form: Ext.fly('test'),method: 'POST',isUpload: true,
		    success:function(response){}
		}); 
	},
	toolsDownload:function(){
		if (!Ext.fly('toolsDownload')){ 
			var frm = document.createElement('form'); 
			frm.id = 'toolsDownload'; 
			frm.style.display = 'none'; 
			document.body.appendChild(frm); 
		} 
		Ext.Ajax.request({ 
			url:Uec3.App.Constants.homeUrl+"/initial/toolsDownload.do",
			form: Ext.fly('toolsDownload'),method: 'POST',isUpload: true,success:function(response){}
		});
	},
	fileSave:function(btn) {
		if(this.initialItem_form_file.getForm().isValid()) {
			this.initialItem_form_file.getForm().submit({
			url : Uec3.App.Constants.homeUrl+'/initial/readExcelData.do',
			method :"post",	
			params : {'initialId' :Ext.isEmpty(this.initial)?"":this.initial.id},
			waitMsg : '正在上传excel文件,请稍后',
			scope:this,
			success : function(form,action){
  				var result=action.result;
				if(result.success=='OK'){
					var data=result.data;
      				if(data){
      					this.createInitialRet(data);
      					this.buttonAjaxRequest("currentorModify",false);
      				}
					Ext.Msg.alert("返回信息","成功上传");
					this.ds_initialItem.baseParams={initialId:this.initial.id};
					this.ds_initialItem.reload();
  				}else{
  					Ext.Msg.alert("返回信息",result.success);
  				}
  				this.initialItem_win_file.hide();
		    	}
		 });
		}
	},
	itemSave:function(btn) {
		var frm = this.itemForm.form;
		var _this=this;
		if(frm.isValid()&&this.validItemForm()){
			var store = _this.initialItem_grid.getStore();
			var obj=frm.getValues();
			var lookupbox=frm.findField("storeId");
			obj.storeName=lookupbox.lastSelectionText;
			frm.submit({
				waitMsg:'请稍后.....',
				waitTitle:'提示',
				url:Uec3.App.Constants.homeUrl+'/initial/initialItemSave.do',
		        params : {
					data : Ext.util.JSON.encode(obj),
					initialJson:Ext.encode(encodeFilte(_this.editForm.form.getValues()))
			    },
			    scope:this,
		        success:function(form,action){
			      	var result=action.result;
			        if(result.success=="OK"){
						if(result.opr=='new'){//新增时操作
							if(result.initial){
								_this.createInitialRet(result.initial);
								_this.buttonAjaxRequest('currentorModify',false);
							}
							var rec=new Ext.data.Record(result.initialItem);
							store.add(rec);
							frm.reset();
							//frm.findField("code").focus(true,300);
						}else if(result.opr=='edit'){//修改时的操作
							var index = store.indexOf(this.initialItem_grid.getSelectionModel().getSelected());
							var item=store.getAt(index);
							for(var fieldName in result.initialItem){
								item.set(fieldName,result.initialItem[fieldName]);
							}
						}
						//刷新initial列表
						this.refreshInitialIndex();
						this.editForm.getForm().setValues(result.initial);
						this.readOnlyForm.getForm().setValues(result.initial);
						store.commitChanges();
						if(result.opr=='edit'){
							_this.itemWindow.hide();
						}
		      		}else{
		      			Ext.Msg.alert("信息",result.success);
		      		}
		        },
			    failure:function(form,action){
			        Ext.Msg.alert('提示','操作失败  ');
			    }
				});
		}else{
			frm.items.each(function(f){
				if(!f.isValid()){
					f.focus(true,300);
					return false;
				}
			});
			
		}
	},
	itemClose:function() {
		this.itemWindow.hide();
	},
	createInitialRet:function(initialT,type){
   		this.initial=initialT;
		if(!type){
			var dataValue=this.editForm.getForm().findField("id").setValue(this.initial.id);
		}else if(type=="all"){
			this.editForm.getForm().setValues(this.initial);
		}
		this.readOnlyForm.getForm().setValues(this.initial);
   		this.ds_initialItem.baseParams={initialId:this.initial.id};
   		this.ds_postPartName_select.baseParams={initialId:this.initial.id};
		Uec3.App.getDesktop().changeWindowUecId("initial_operation","initial_operation_"+this.initial.id);   
		this.changeTaskButtonText(this.initial.code);
   	},
   	changeTaskButtonText:function(code){
		this.taskButton.setText("期初单:"+code);
	},
	//按钮加载
   	buttonAjaxRequest:function(typeId,mark,fn){
   		var _this=this;
   		this.buttonAjax.request({
		 	url:Uec3.App.Constants.homeUrl+'/initial/buttonPanel.do',
		 	params:{typeId:typeId},
		 	scope:_this,
		 	success:function(response,options){
		 		_this.isMaskWindow("buttons");
		 		var reslut = Ext.decode(response.responseText);
		 		_this.removeButtonPanel();
		 		var btnPanel=_this.addButtonPanel(reslut.buttons);// 初始按钮
		 		if(!Ext.CUR_APP.hasPermission(31)){
		 			btnPanel.hide();
		 		}
		 		//是否遮罩
   				this.isMark(mark);
   				if(Ext.isFunction(fn))fn(reslut);
		 	}
		});
   	},
    autoFillDetailForm:function(){
		var source = this.itemForm.form.findField("source").getValue();
		var code = this.itemForm.form.findField("code").getValue();
		if(!code)return;
	 	Ext.Ajax.request({
	        url :Uec3.App.Constants.homeUrl+"/part/queryPart!getPartByCodeAndSource.do",
		    params :{queryParam:Ext.encode({code:code,source:source})},
		    method :"post",
		    scope:this,
		    callback :function(options,success,response){},
		    success:function(response,options){	                	 
		    	  var part = Ext.decode(response.responseText);
		    	  if(part){
		    	  	 this.itemForm.getForm().findField("tempName").setValue(part.name);
		    	  	 this.itemForm.getForm().findField("name").setValue(part.name);
		    	  	 this.itemForm.getForm().findField("measurementUnit").setValue(part.measurementUnit);
		    	  }else{
		    	     Ext.MessageBox.alert("提示","此零件编码和来源无相关零件信息,请重试");
		    	     this.itemForm.getForm().findField('source').clearValue();
		    	     this.itemForm.getForm().findField('code').clearValue();
		    	  }
			       
		    },
	    failure:function(response,options){Ext.MessageBox.alert("提示","数据加载异常");}
	 	});	    		  
    },
    show:function(){
    	Uec3.initialOperationWin.superclass.show.call(this);
    	//console.debug(this.readOnlyForm);
    },
    fEAfterShow:function(){
   		this.windowLoadMask.show();
   			 this.itemFormSourceCombo.getStore().load();//来源store加载
   			 if(this.params&&this.params.id){
	 			this.editForm.getForm().load({
	   				url:Uec3.App.Constants.homeUrl+'/initial/getInitialById.do',
	   				params:{id:this.params.id},
	   				scope:this,
	   				success:function(form,action){
	   					this.isMaskWindow("initialFormPanel");
	   					this.createInitialRet(action.result.data,"all");
	   					var userId=action.result.userId;
	   					if(this.initial.status==0){
		   					if(this.initial.currentorId==userId){
		   						this.buttonAjaxRequest("currentorModify",false);
		   					}else{
		   						this.buttonAjaxRequest("notCurModify",true);
		   					}
	   					}else if(this.initial.status==1){
	   						this.buttonAjaxRequest("formal",true);
	   					}
	   					if(!this.initial.gmtAccept){
							this.editForm.getForm().findField('gmtAccept').setValue((new Date()).dateFormat('Y-m-d'));
						}
						this.readOnlyForm.getForm().loadRecord(this.initial);
		   				this.ds_initialItem.load();    // 加载initialItem表格数据  					
	   				}
		   		});//主表form加载
   			 }else{
   			 	this.isMaskWindow("initialFormPanel");
   			 	this.buttonAjaxRequest("new",false);
   			 	this.editForm.form.findField('gmtAccept').setValue((new Date()).dateFormat('Y-m-d'));
   			 }
    },
    /*提交后的操作*/
	aftersubmitFunc:function(form,action){
		var _this=this;
		_this.buttonAjaxRequest("formal",true,function(){
		_this.refreshInitialIndex();
		var result=action.result;
		if(result.errorInitial){
			Ext.MessageBox.show({title:"信息",msg:"错误期初零件明细在单据号为"+result.errorInitial.code+"里",buttons:Ext.MessageBox.OK,fn:function(){
				_this.redirectUrl("initial_operation",{id:result.errorInitial.id,winId:result.errorInitial.id});
			}});
		}else if(result.initial){
			_this.editForm.getForm().setValues(result.initial);
			_this.readOnlyForm.getForm().setValues(result.initial);
		}
		});
	},
	isItemGridValid:function(){
   		var obj=this.editForm.form.getValues();
   		if(obj.id){
   			return true;
   		}else{
   			if(this.initialItem_grid.getStore().getCount()>0){
   				return true;
   			}
   		}
   		return false;
   	},
   	validItemForm:function(){
		var minOnHand=this.itemForm.getForm().findField("minOnHand").getValue();
		var maxOnHand=this.itemForm.getForm().findField("maxOnHand").getValue();
		if(minOnHand>maxOnHand){
			Ext.Msg.alert("提示","上限库存应大于下限库存");
			return false;
		}
		return true;
	},
	/*新建单据*/
	initialNew:function(btn){
		this.redirectUrl("initial_operation");
	},
	/*接手单据*/
    initialRecieve:function(btn){
    	var _this=this;
    	Ext.Msg.confirm("提示",((this.initial.currentorName==null||this.initial.currentorName=='')?"无人":this.initial.currentorName)+"在处理,确定要接手?",function(btn2){
			if(btn2=="yes"){
				_this.formSubmit(btn.url,function(form,action){
					_this.buttonAjaxRequest("currentorModify",false,function(result){
					Ext.Msg.alert("信息","接手成功");
					Ext.Msg.hide.defer(600,Ext.Msg);
					});
				});
			}
		});
	},
	/*释放单据*/
	initialRelease:function(btn){
		var _this=this;
		var fn=function(form,action){
			_this.initial.currentorName=null;
			_this.buttonAjaxRequest("notCurModify",true,function(result){
				Ext.Msg.alert("信息","释放成功");
				Ext.Msg.hide.defer(600,Ext.Msg);
			});
		}
		this.formSubmit(btn.url,fn);
	},

	/*查看期初列表*/
	initialView:function(btn){
		this.refreshInitialIndex();
		this.redirectUrl('initial_index');
	},
	/*后台ajax传递函数*/
	formSubmit:function(url,fn,obj){
		var result;
		var params={waitMsg:'请稍后.....',waitTitle:'提示',url:url,
	        method :"post",timeout:1800000,
	        success:function(form,action){
	      		result=action.result;
	      		if(result.success=='OK'){
		  			if(Ext.isFunction(fn))fn(form,action);
		  		}else{
		  			Ext.Msg.alert('信息',result.success); 
		  		}
	       	},
			failure:function(form,action){
	        	Ext.Msg.alert('提示','本地网络问题,请稍后连接!');
	      	}
		};
		if(obj)Ext.apply(params,obj);
		this.editForm.form.submit(params);
		return result;
	},
	/*保存*/
	initialSave:function(btn){
		var _this=this;
		if(_this.isItemGridValid()){
			var result=_this.formSubmit(btn.url,function(form,action){
				_this.buttonAjaxRequest("currentorModify",false,function(){
					Ext.Msg.alert('提示','保存成功 ');
					Ext.Msg.hide.defer(700,Ext.Msg);
				});				
			},_this.getInitialFormPanelObj());
		}else{
			Ext.Msg.alert('提示','请至少加一条明细记录  ');
			Ext.Msg.hide.defer(700,Ext.Msg);
		}
	},
	/*提交*/
	initialSubmit:function(btn){
		var _this=this;
		if(_this.editForm.form.isValid()){
		if(_this.isItemGridValid()){
		 	_this.editForm.form.submit({
				waitMsg:'请稍后.....',waitTitle:'提示',
				url:Uec3.App.Constants.homeUrl+'/initial/countErrors.do',
				scope:_this,
		        success:function(form,action){
			      	var result=action.result;
			      	if(result.success=='OK'){
			      		if(result.correctCount==0){
			      			Ext.Msg.show({title:'错误',msg: '没用一条正确的数据,请重新修改再提交',	buttons: Ext.Msg.OK,icon: Ext.MessageBox.ERROR});
			      			return;
			      		}else if(result.errorCount==0&&result.warnCount==0){
			      			this.formSubmit(btn.url,this.aftersubmitFunc.createDelegate(this),this.getInitialFormPanelObj());
			      		}else if(result.errorCount>0||result.warnCount>0){
					  		var str='';
					  		if(result.errorCount>0){
					  			str+=result.errorCount + '个零件错误.';
					  		}
					  		if(result.warnCount>0){
					  			str+=result.warnCount + ' 个零件警告.';
					  		}
					  		if(result.errorCount>0||result.warnCount>0){
					  			str+='确定要提交吗?'
					  		}
					  		Ext.Msg.show({
			      				title:'错误',msg: str,
							   	buttons: Ext.Msg.YESNO,
							   	icon: Ext.MessageBox.WARNING,
							   	scope:this,
								fn:function(btn2){
									if(btn2=="yes"){
										this.formSubmit(btn.url,this.aftersubmitFunc.createDelegate(this),this.getInitialFormPanelObj.createDelegate(this)());
									}
								}
			      			});
			      		}
				  	}else{
				  		Ext.Msg.alert('信息',result.success); 
				    }
		      	},
		        failure:function(form,action){
		        	Ext.Msg.alert('提示','提交失败');
		      	}
			});
		}else{
			Ext.Msg.alert('提示','请至少加一条明细记录');
		}
		}else{
			Ext.Msg.alert('提示','请正确填写必填项!');
			
		}
	},
	getInitialFormPanelObj:function(){
		return {params:{data:Ext.encode(encodeFilte(this.editForm.getForm().getValues()))}};
	},
	/*删除*/
	initialDelete:function(btn){
		var _this=this;
		Ext.Msg.confirm("提示","确定删除此期初单",function(btn2){
			if(btn2=="yes"){
			    _this.formSubmit(btn.url,function(){
			    	_this.redirectUrl('initial_index');
			    	__this.refreshInitialIndex();
			    });
			}
		});
	},
	/*打印*/
	initialPrint:function(){
	},
	/*返回*/
	initialClose:function(){
		this.close();
	},
	isMark:function(isMark){
		var topToolbar=this.initialItem_grid.getTopToolbar();
		this.editForm.form.findField("gmtAccept").enable();
		this.editForm.form.findField("memo").enable();
		topToolbar.getComponent('add').enable();
		topToolbar.getComponent('edit').enable();
		topToolbar.getComponent('delete').enable();
		topToolbar.getComponent('upload').enable();
		if(isMark==true){
			this.editForm.form.findField("gmtAccept").disable();
			this.editForm.form.findField("memo").disable();
			topToolbar.getComponent('add').disable();
			topToolbar.getComponent('edit').disable();
			topToolbar.getComponent('delete').disable();
			topToolbar.getComponent('upload').disable();
		}
	},
    isMaskWindow:function(obj){
    	this.wMaskCol.add({id:obj});
    	if(this.windowLoadMask&&this.wMaskCol.getCount()==2){
    		this.windowLoadMask.hide();
    		this.wMaskCol.clear();
    	}
    },
    redirectUrl:function(id,params){
    	var desktop =Uec3.App.getDesktop();   
		desktop.launchWindowByParam(id,params); 
		
    },
   	refreshInitialIndex:function(){
		var window =Uec3.App.getDesktop().getWindowByUecId("initial_index");   
		if(window){
			var store=window.moduleObj.getObjByKey("store");
			store.reload();
		}   		
   	},
    fEMaxOnHandField:function(field){
	    var maxOnHand=field.getValue();
		var minOnHand=this.itemForm.form.findField('minOnHand').getValue();
		if(minOnHand>maxOnHand){
			Ext.Msg.alert("提示","上限库存应大于下限库存");
		}	
    },
    fEPostPartNameCombo:function(combo,record){
    	var grid=this.initialItem_grid;
		var isExit=Ext.each(grid.getStore().getRange(),function(record_ds){
			if(record_ds.data.id==record.data.id){
				return false;
			}
		});
		if(!Ext.isNumber(isExit)){
			this.ds_initialItem_other.baseParams.id=record.data.id;
			this.ds_initialItem_other.load();
		}else{
			var sm=grid.getSelectionModel();
			var selecteReord=sm.getSelected();
			if((selecteReord&&selecteReord.data.id!=record.data.id)||!selecteReord){
				var rec=grid.getStore().getById(record.data.id);
				var index=this.ds_initialItem.indexOf(rec);
				sm.selectRow(index);
			}else if(selecteReord&&selecteReord.data.id==record.data.id){
				
			}else{
				
			}
		}
	},
	fEItemOtherBeforeLoad:function(store,options){
		store.baseParams.initialId=this.ds_initialItem.baseParams.initialId;
		Ext.MessageBox.show({title : "提示",msg : "加载中,请稍后.....",buttons: false,closable:false,width:200,wait:true,modal:true});
	},
	fEItemOtherLoa:function(store,records){
		var num=this.ds_initialItem.getRange().length;
		this.ds_initialItem.add(records);
		var sm=this.initialItem_grid.getSelectionModel();
		sm.selectRow(num);
		this.initialItem_grid.getView().focusRow(num); 
		Ext.MessageBox.hide();
	}
	
	});
	
Uec3.initialOperationWindow = Ext.extend(Ext.app.Module, {
   	id: 'initial_operation',
   	permissionId:31,
    createWindow : function(params,fn){
   	  var windowId='initial_operation';
   	  if(params&&params.winId){
   	  	windowId+="_"+params.winId;
   	  }
      var desktop = Uec3.App.getDesktop();
      var win = desktop.getWindowByUecId(windowId);
      var module=this;
      if(!win){
         win = desktop.createWindow({
         	uecId:windowId,
            title: '新增期初单',
            width: 1000,
           	height: 500,
           	params:params,
            iconCls: 'acc-icon',
            constrainHeader: true,
            layout:"vbox",
            layoutConfig:{
            	align:'stretch'
            },
            maximizable: true
         },Uec3.initialOperationWin);     
      } 
      if(Ext.isFunction(fn))fn();
      win.show();
   }	
});